package com.juguo.charginganimation.View.activity;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.app.ActivityOptionsCompat;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.chad.library.adapter.base.module.BaseLoadMoreModule;
import com.google.gson.Gson;
import com.juguo.charginganimation.Adapter.FavoritesGalleryAdapter;
import com.juguo.charginganimation.Base.Baseactivty;
import com.juguo.charginganimation.Bean.FavoritesListBean;
import com.juguo.charginganimation.Data.remote.RetrofitManager;
import com.juguo.charginganimation.MainApplication;
import com.juguo.charginganimation.R;
import com.juguo.charginganimation.utils.RxUtils;
import com.juguo.charginganimation.utils.ToastUtil;
import com.juguo.charginganimation.utils.UITools;
import com.juguo.charginganimation.View.gallery.GalleryDetailFavorites;
import com.juguo.charginganimation.View.gallery.GalleryViewModel;
import com.juguo.charginganimation.repository.PixabayService;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.disposables.CompositeDisposable;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class FavoritessActivity extends Baseactivty {
    private String TAG = "FeaturedFragment";
    private Context mContext;
    private ImageButton deletFavorites;
    //图片瀑布流
    private RecyclerView viewPager;
    private SwipeRefreshLayout swipeRefreshLayout;

    private CompositeDisposable mDisposable = new CompositeDisposable();

    private FavoritesGalleryAdapter galleryAdapter;
    private BaseLoadMoreModule loadMore;
    //暂存当前页数
    private int currentPage = 1;

    //暂存总页数
    private int totalPage = 1;
    /**
     * 数据源
     */
    private GalleryViewModel mViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_favoritess);
        mViewModel = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(GalleryViewModel.class);

        UITools.makeStatusBarTransparent(this);
        UITools.setMIUI(this, true);
        viewPager = findViewById(R.id.recyclerview_gallery_favorites);
        swipeRefreshLayout = findViewById(R.id.swipeGallery_favorites);

        galleryAdapter = new FavoritesGalleryAdapter();
        galleryAdapter.setDiffCallback(new MyDiffCallback());
        //开启滑动动画
        galleryAdapter.setAnimationEnable(true);

        //动画只执行一次
        galleryAdapter.setAnimationFirstOnly(false);

        //设置空视图
        galleryAdapter.setEmptyView(initEmptyView("没有更多数据..."));

        //加载更多对象，来自于BRVAH
        loadMore = galleryAdapter.getLoadMoreModule();
        loadMore.isAutoLoadMore();

        //交错布局，2列，纵向
        viewPager.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        viewPager.setAdapter(galleryAdapter);

        //数据源：hitsBean观察者，如果hitsBean发生变化则更新recycleView
        mViewModel.favorites.observe(this, favorites -> {
            if (mViewModel.favorites.getValue() == null) {
                mViewModel.favoritesList();
            }
            galleryAdapter.setDiffNewData(favorites);
            swipeRefreshLayout.setRefreshing(false);
            //数据发生变化时，重新获取总页数
            totalPage = mViewModel.getTotalPage();
        });

        //如果_hitsBean为空，则获取数据
        if (mViewModel.favorites.getValue() == null) {
            mViewModel.favoritesList();
            //重新获取页数
            currentPage = mViewModel.getCurrentPage() + 1;
        }

        //下拉刷新
        swipeRefreshLayout.setOnRefreshListener((SwipeRefreshLayout.OnRefreshListener) () -> {
            mViewModel.favoritesList();
            //重新获取页数
            currentPage = mViewModel.getCurrentPage() + 1;
            loadMore.loadMoreComplete();
        });

        //Item点击事件,进入详细页面
        galleryAdapter.setOnItemClickListener((adapter, view, position) -> {
            //将图片信息传输到detail页面
            Bundle bundle = new Bundle();
            bundle.putParcelable("CHECKED_PHOTO_ID", (Parcelable) adapter.getItem(position));
            Intent intent = new Intent(FavoritessActivity.this, GalleryDetailFavorites.class);
            intent.putExtras(bundle); //传bundle对象
            //过度效果
            ActivityOptionsCompat compat = ActivityOptionsCompat.makeSceneTransitionAnimation(FavoritessActivity.this, view, "detail_img");
            ActivityCompat.startActivity(FavoritessActivity.this, intent, compat.toBundle());
        });

        /**
         * 当recycleView滑动到底部时执行此监听
         */
        loadMore.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                loadMoreGallery();
            }
        });
        deletImages();
    }


    /**
     * 加载更多数据
     */
    private void loadMoreGallery() {
        Log.d(TAG, "加载更多 -> currentPage：" + currentPage + "\t totalPage：" + totalPage + "\tkey：");
        if (currentPage > totalPage) {
            loadMore.loadMoreEnd();
            return;
        } else {
            mViewModel.favoritesList();
        }
    }

    private View initEmptyView(String tip) {
        View emptyView = getLayoutInflater().inflate(R.layout.view_pray, null);
        TextView emptyTextView = emptyView.findViewById(R.id.emptytextView);
        emptyTextView.setText(tip);
        return emptyView;
    }

    // delet图片
    private void deletImages() {
        deletFavorites = findViewById(R.id.ic_delet_facorites_btn);
        deletFavorites.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //更新布局
                PixabayService service = RetrofitManager.getInstance().getRetrofit().create(PixabayService.class);
                Map<String, Object> map = new HashMap<>();
                map.put("starType", 2);
                map.put("resIdList", galleryAdapter.getListId());
                //{"param":{map}}
                Map<String, Object> param = new HashMap<>();
                param.put("param", map);
                RequestBody body = RequestBody.create(MediaType.get("application/json; charset=utf-8"), new Gson().toJson(param));
                mDisposable.add(service.deleteFavoritesList(body)
                        .compose(RxUtils.schedulersTransformer())
                        .subscribe((baseBean -> {
                            mViewModel.favoritesList();
//                            ToastUtil.showLongToast(MainApplication.getsInstance(), "删除成功");
                            Log.d(TAG, "accept: " + new Gson().toJson(baseBean));
                        }), throwable -> Log.d(TAG, "loadMore: " + throwable)));
            }
        });
    }

    /**
     * 指定DiffUtil类，判断item是否相同
     */
    static class MyDiffCallback extends DiffUtil.ItemCallback<FavoritesListBean.Favorites> {
        @Override
        public boolean areItemsTheSame(@NonNull FavoritesListBean.Favorites oldItem, @NonNull FavoritesListBean.Favorites newItem) {
            return oldItem.getId() == newItem.getId();
        }

        @SuppressLint("DiffUtilEquals")
        @Override
        public boolean areContentsTheSame(@NonNull FavoritesListBean.Favorites oldItem, @NonNull FavoritesListBean.Favorites newItem) {
            return oldItem.equals(newItem);
        }
    }
}